<?php
declare (strict_types=1);

namespace app\common\model;

use addons\Target\facade\Target;
use think\Exception;
use think\facade\Cache;
use think\facade\Db;
use think\facade\Log;

class Pintuan extends Base
{
    public static function submit($param, $user):array
    {
        try {
            parent::startTrans();
            $qianggouxiaohao = self::checkpintuan($param['pid'],$user);
            Target::Account()->basics($user->id,'qianggou',$qianggouxiaohao,'拼团抢购','-')->createNormal();
            $param['uid'] = $user->id;
            $param['pintuan_date'] = date('Y-m-d');
            $param['qianggou_cost'] = $qianggouxiaohao;
            Pintuan::create($param);
            parent::commit();
            return ['code' => 1];

        } catch (\Exception $e) {
            parent::rollback();
            return ['code' => -1, 'msg' => $e->getMessage()];
        }

    }

    public static function checkpintuan($pid,$user){
        if (empty($pid)) {
            throw new \Exception('请选择拼团商品');
        }
        $product = Product::where(['id' => $pid])->find();
        if (empty($product)) {
            throw new \Exception('未获取到商品信息');
        }
        $system = Cache::get('system');
        if($system['qiangou_open'] != 1 ){
            throw new \Exception('拼团活动已关闭');
        }
        if (!empty($system['qianggou_times'])) {
            $times = explode(' - ', $system['qianggou_times']);
            $his = date('H:i:s');
            if ($his < $times[0] || $his > $times[1]) {
                throw new \Exception('拼团抢购时间为：' . $times[0] . ' ~ ' . $times[1]);
            }
        }
        $userassets = Assets::where(['uid'=>$user->id])->find();
        if (empty($userassets) || $userassets['qianggou'] < $system['qianggou_per_cost'] ){
            throw new \Exception('用户抢购积分余额不足，本次抢购需消耗'.$system['qianggou_per_cost'].'抢购积分');
        }
        return $system['qianggou_per_cost'];
    }

    public static function zhongjiang($test=false): array
    {
        Log::write("test=".$test);
        try {
            parent::startTrans();
            $system = Cache::get('system');
            if (!empty($system['qianggou_times'])) {
                $times = explode(' - ', $system['qianggou_times']);
                $his = date('H:i:s');
                $date = date('Y-m-d');
                if ($his < $times[1]) {
                    throw new \Exception('今天活动还未开始');
                }
            }
            $chenggonglv = $system['qianggou_success']; //抢购率
            $qianggoulistids = parent::where(['status' => 1, 'pintuan_date' => $date])->column('id');
            $count = count($qianggoulistids); // 总数
            if($count < 1){
                throw new \Exception('暂无抢购订单');
            }

            $chenggongshu = (int) ceil($count * $chenggonglv) ; // 成功数
            shuffle($qianggoulistids); //打乱
            $chenggongids = array_slice($qianggoulistids,0,$chenggongshu); //随机取成功数个数

            parent::whereIn('id',$chenggongids)->save(['status'=>2]);//处理中奖状态

            $shibaiids = array_slice($qianggoulistids,$chenggongshu,$count);
            if(!empty($shibaiids)){

                parent::whereIn('id',$shibaiids)->save(['status'=>3]);//处理未中奖状态
            }

            parent::commit();
            return ['code' => 1, 'msg' => '执行成功'];
        } catch (\Exception $e) {
            parent::rollback();
            Logs::write('logs/qianggouzhongjiang.log', $e->getMessage());

            return ['code' => -1, 'msg' => $e->getMessage()];
        }

    }

    public static function succssFanyong($test=false): array
    {

        try {
            parent::startTrans();
            $system = Cache::get('system');
            if($test){
                $yesterday = date('Y-m-d');
            }else{
                $yesterday = date('Y-m-d', strtotime('-1 day'));
            }

            //

            $sql = " select group_concat(`order_id`) as order_ids ,uid from pintuan where `status` = 2 and pintuan_date = '$yesterday' and is_fanyong =2 and order_id > 0 group by uid ";
            $cp = Db::query($sql);
            if(empty($cp)){
                throw new \Exception('没有满足条件的拼团订单');
            }
            foreach ($cp as $k => $item) {
               if(empty($amount = Order::whereIn('id',$item['order_ids'])->where(['pay_state'=>1,'uid'=>$item['uid']])->sum('real_amount'))) {
                    continue;
               }
               $tz_lock = Assets::where(['uid'=>$item['uid']])->value('tz_lock');
               $dongjie = $amount * $system['qianggou_fan_tongzheng'];
               $xiaofei = $amount * $system['qianggou_fan_xiaofei'];
               $shifang = $tz_lock *  $system['qianggou_tongzheng_shifang'];
                Target::Account()->basics($item['uid'],'consume',$xiaofei,'拼团抢购返佣','+')->createNormal();
                Target::Account()->basics($item['uid'],'tz_use',$shifang,'抢购成功释放通证积分','+')->createNormal();
                Target::Account()->basics($item['uid'],'tz_lock',$shifang,'抢购成功释放通证积分,冻结减少','-')->createNormal();
                Target::Account()->basics($item['uid'],'tz_lock',$dongjie,'抢购成功增加冻结通证积分','+')->createNormal();
                User::where(['id'=>$item['uid']])->save(['is_qianggou'=>1]); //更新该用户已抢购成功条件
                parent::whereIn('order_id',$item['order_ids'])->save(['is_fanyong'=>1]);
            }
            parent::commit();
            return ['code' => 1, 'msg' => '执行成功'];
        } catch (\Exception $e) {
            parent::rollback();
            Logs::write('logs/qianggouchengongfanyong.log', $e->getMessage());

            return ['code' => -1, 'msg' => $e->getMessage()];
        }

    }


    public static function failFanyong($test=false): array
    {

        try {
            parent::startTrans();
            $system = Cache::get('system');

            if($test){
                $yesterday = date('Y-m-d');
            }else{
                $yesterday = date('Y-m-d', strtotime('-1 day'));
            }

            $sql = " select sum(`qianggou_cost`) as total_cost , uid from pintuan where `status` = 3 and pintuan_date = '$yesterday' and is_fanyong =2 group by uid ";
            $pintuanlist = Db::query($sql);

            if(empty($pintuanlist)){
                throw new \Exception('没有满足条件的失败拼团订单');
            }
            foreach ($pintuanlist as $k => $item) {

                $fuli = $item['total_cost'] * $system['qianggoub_fan_fuli'];

                Target::Account()->basics($item['uid'],'qianggou',$item['total_cost'],'抢购不成功返回抢购积分','+')->createNormal();
                Target::Account()->basics($item['uid'],'welfare',$fuli,'抢购不成功返福利积分','+')->createNormal();

            }
            parent::where(['status'=>3,'pintuan_date'=>$yesterday])->save(['is_fanyong'=>1]);
            parent::commit();
            return ['code' => 1, 'msg' => '执行成功'];
        } catch (\Exception $e) {
            parent::rollback();
            Logs::write('logs/qianggoushibaifanyong.log', $e->getMessage());

            return ['code' => -1, 'msg' => $e->getMessage()];
        }

    }

    public static function succssFanyongp(): array
    {
        try {
            parent::startTrans();
            $system = Cache::get('system');

            $wherec = [];
            $wherec['status'] = 2;
            $wherec['is_fanyong'] = 1;
            $wherec['is_pfanyong'] = 2;
            $wherec[] = ['parent_id','>',0];
            $plist = parent::where($wherec)->select();

            if(empty($plist)){
                throw new \Exception('没有满足条件的邀请拼团订单');
            }

            foreach ($plist as $item) {
                if(empty($item->order_id)){
                    continue;
                }
                if(empty($orderinfo = Order::where(['id'=>$item->order_id,'pay_state'=>1])->find())){
                    continue;
                }

                $fuli = $orderinfo->real_amount * $system['qianggoup_fan_fuli'];
                Target::Account()->basics($item->parent_id,'welfare',$fuli,'抢购成功返给拼团邀请人','+')->createNormal();
                parent::where(['id'=>$item->id])->save(['is_pfanyong'=>1]);

            }

            parent::commit();
            return ['code' => 1, 'msg' => '执行成功'];
        } catch (\Exception $e) {
            parent::rollback();
            Logs::write('logs/qianggouchengongfanyongp.log', $e->getMessage());

            return ['code' => -1, 'msg' => $e->getMessage()];
        }

    }

}